Impact of Macroeconomic Factors on Amazon Stock Price
The Consumer Discretionary sector comprises companies that produce non-essential goods and services, such as apparel, entertainment, and luxury items. One of the top companies in this sector is Amazon.com, Inc. (AMZN), which has revolutionized the retail industry by providing customers with an online platform to purchase a wide range of products.
By using an ARIMAX+ARCH/GARCH model to analyze the stock price behavior of Amazon, we can gain insights into how macroeconomic factors impact the company’s performance. For example, an increase in GDP growth rate or a decrease in unemployment rate may lead to increased consumer spending and a rise in Amazon’s stock price. Conversely, an increase in inflation or interest rates may lead to a decrease in consumer spending and a decline in Amazon’s stock price.
Time series Plot
Code
# get data
options("getSymbols.warning4.0"=FALSE)
options("getSymbols.yahoo.warning"=FALSE)
data.info = getSymbols("AMZN",src='yahoo', from = '2010-01-01',to = "2023-03-01",auto.assign = FALSE)
data = getSymbols("AMZN",src='yahoo', from = '2010-01-01',to = "2023-03-01")
df <- data.frame(Date=index(AMZN),coredata(AMZN))
# create Bollinger Bands
bbands <- BBands(AMZN[,c("AMZN.High","AMZN.Low","AMZN.Close")])
# join and subset data
df <- subset(cbind(df, data.frame(bbands[,1:3])), Date >= "2010-01-01")
# colors column for increasing and decreasing
for (i in 1:length(df[,1])) {
if (df$AMZN.Close[i] >= df$AMZN.Open[i]) {
df$direction[i] = 'Increasing'
} else {
df$direction[i] = 'Decreasing'
}
}
i <- list(line = list(color = '#7FB3D5'))
d <- list(line = list(color = '#7F7F7F'))
# plot candlestick chart
fig <- df %>% plot_ly(x = ~Date, type="candlestick",
open = ~AMZN.Open, close = ~AMZN.Close,
high = ~AMZN.High, low = ~AMZN.Low, name = "AMZN",
increasing = i, decreasing = d)
fig <- fig %>% add_lines(x = ~Date, y = ~up , name = "B Bands",
line = list(color = '#ccc', width = 0.5),
legendgroup = "Bollinger Bands",
hoverinfo = "none", inherit = F)
fig <- fig %>% add_lines(x = ~Date, y = ~dn, name = "B Bands",
line = list(color = '#ccc', width = 0.5),
legendgroup = "Bollinger Bands", inherit = F,
showlegend = FALSE, hoverinfo = "none")
fig <- fig %>% add_lines(x = ~Date, y = ~mavg, name = "Mv Avg",
line = list(color = '#C052B3', width = 0.5),
hoverinfo = "none", inherit = F)
fig <- fig %>% layout(yaxis = list(title = "Price"))
# plot volume bar chart
fig2 <- df
fig2 <- fig2 %>% plot_ly(x=~Date, y=~AMZN.Volume, type='bar', name = "AMZN Volume",
color = ~direction, colors = c('#7FB3D5','#7F7F7F'))
fig2 <- fig2 %>% layout(yaxis = list(title = "Volume"))
# create rangeselector buttons
rs <- list(visible = TRUE, x = 0.5, y = -0.055,
xanchor = 'center', yref = 'paper',
font = list(size = 9),
buttons = list(
list(count=1,
label='RESET',
step='all'),
list(count=3,
label='3 YR',
step='year',
stepmode='backward'),
list(count=1,
label='1 YR',
step='year',
stepmode='backward'),
list(count=1,
label='1 MO',
step='month',
stepmode='backward')
))
# subplot with shared x axis
fig <- subplot(fig, fig2, heights = c(0.7,0.2), nrows=2,
shareX = TRUE, titleY = TRUE)
fig <- fig %>% layout(title = paste("Amazon Stock Price: January 2010 - March 2023"),
xaxis = list(rangeselector = rs),
legend = list(orientation = 'h', x = 0.5, y = 1,
xanchor = 'center', yref = 'paper',
font = list(size = 10),
bgcolor = 'transparent'))
figCode
log(data.info$`AMZN.Adjusted`) %>% diff() %>% chartSeries(theme=chartTheme('white'),up.col='#7FB3D5')Code
#import the data
gdp <- read.csv("DATA/RAW DATA/gdp-growth.csv")
#change date format
gdp$Date <- as.Date(gdp$DATE , "%m/%d/%Y")
#drop DATE column
gdp <- subset(gdp, select = -c(1))
#export the cleaned data
gdp_clean <- gdp
write.csv(gdp_clean, "DATA/CLEANED DATA/gdp_clean_data.csv", row.names=FALSE)
#plot gdp growth rate
fig <- plot_ly(gdp, x = ~Date, y = ~value, type = 'scatter', mode = 'lines',line = list(color = 'rgb(240, 128, 128)'))
fig <- fig %>% layout(title = "U.S GPD Growth Rate: 2010 - 2022",xaxis = list(title = "Time"),yaxis = list(title ="GDP Growth Rate"))
figCode
#import the data
inflation_rate <- read.csv("DATA/RAW DATA/inflation-rate.csv")
#cleaning the data
#remove unwanted columns
inflation_rate_clean <- subset(inflation_rate, select = -c(1,HALF1,HALF2))
#convert the data to time series data
inflation_data_ts <- ts(as.vector(t(as.matrix(inflation_rate_clean))), start=c(2010,1), end=c(2023,2), frequency=12)
#export the data
write.csv(inflation_rate_clean, "DATA/CLEANED DATA/inflation_rate_clean_data.csv", row.names=FALSE)
#plot inflation rate
fig <- autoplot(inflation_data_ts, ylab = "Inflation Rate", color="#FFA07A")+ggtitle("U.S Inflation Rate: January 2010 - February 2023")+theme_bw()
ggplotly(fig)Code
#import the data
interest_data <- read.csv("DATA/RAW DATA/interest-rate.csv")
#change date format
interest_data$Date <- as.Date(interest_data$Date , "%m/%d/%Y")
#export the cleaned data
interest_clean_data <- interest_data
write.csv(interest_clean_data, "DATA/CLEANED DATA/interest_rate_clean_data.csv", row.names=FALSE)
#plot interest rate
fig <- plot_ly(interest_data, x = ~Date, y = ~value, type = 'scatter', mode = 'lines',line = list(color='rgb(219, 112, 147)'))
fig <- fig %>% layout(title = "U.S Interest Rate: January 2010 - March 2023",xaxis = list(title = "Time"),yaxis = list(title ="Interest Rate"))
figCode
#import the data
unemployment_rate <- read.csv("DATA/RAW DATA/unemployment-rate.csv")
#change date format
unemployment_rate$Date <- as.Date(unemployment_rate$Date , "%m/%d/%Y")
# export the data
write.csv(unemployment_rate, "DATA/CLEANED DATA/unemployment_rate_clean_data.csv", row.names=FALSE)
#plot unemployment rate
fig <- plot_ly(unemployment_rate, x = ~Date, y = ~Value, type = 'scatter', mode = 'lines',line = list(color = 'rgb(189, 183, 107)'))
fig <- fig %>% layout(title = "U.S Unemployment Rate: January 2010 - March 2023",xaxis = list(title = "Time"),yaxis = list(title ="Unemployment Rate"))
figFrom 2010 to 2023, Amazon’s stock experienced significant growth as the company expanded its operations and diversified its offerings. In 2010, Amazon was primarily known as an online retailer of books, electronics, and other consumer goods. However, over the next several years, the company expanded into new markets, including streaming video and music, cloud computing services, and even physical retail stores.
Throughout this period, Amazon’s stock price saw consistent growth, although there were occasional dips in response to macroeconomic events or company-specific news. For example, the company’s stock price declined in 2014 amid concerns about its profitability and increased competition in the retail industry. However, Amazon’s stock quickly rebounded as the company continued to innovate and expand into new markets.
In recent years, Amazon’s stock price has been impacted by a variety of factors, including the COVID-19 pandemic and increased scrutiny from regulators. Nevertheless, the company’s strong position in the e-commerce and cloud computing markets, as well as its continued investment in new technologies and initiatives, have helped to maintain investor confidence in Amazon’s long-term growth potential.
Since early 2021, Amazon’s stock price has experienced some volatility, likely due to a combination of factors such as global economic uncertainty and fluctuations in consumer demand for the company’s products.
As discussed before, the macroeconomic factors of GDP growth, inflation, interest rates, and unemployment rate are closely interrelated and play a crucial role in the overall health and stability of an economy. From 2010 to 2023, the global economy experienced a mix of ups and downs, with periods of strong GDP growth followed by slowdowns and recessions.
The second plot shows the first difference of the logarithm of the adjusted Amazon stock price. Taking the first difference removes any long-term trends and transforms the time series into a stationary process. From the plot, we can observe that the first difference of the logarithm of the Amazon stock price appears to be stationary, as the mean and variance are roughly constant over time.
Enodogenous and Exogenous Variables
Code
numeric_data <- c("AMZN.Adjusted","gdp", "interest", "inflation", "unemployment")
numeric_data <- final[, numeric_data]
normalized_data_numeric <- scale(numeric_data)
normalized_data <- ts(normalized_data_numeric, start = c(2010, 1), end = c(2021,10),frequency = 4)
ts_plot(normalized_data,
title = "Normalized Time Series Data for AMZN Stock and Macroeconomic Variables",
Ytitle = "Normalized Values",
Xtitle = "Year")Code
# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
cormat[lower.tri(cormat)]<- NA
return(cormat)
}
cormat <- round(cor(normalized_data_numeric),2)
upper_tri <- get_upper_tri(cormat)
melted_cormat <- melt(upper_tri, na.rm = TRUE)
# Create a ggheatmap
ggheatmap <- ggplot(melted_cormat, aes(Var2, Var1, fill = value))+
geom_tile(color = "white")+
scale_fill_gradient2(low = "blue", high = "red", mid = "white",
midpoint = 0, limit = c(-1,1), space = "Lab",
name="Pearson\nCorrelation") +
theme_minimal()+ # minimal theme
theme(axis.text.x = element_text(angle = 45, vjust = 1,
size = 12, hjust = 1))+
coord_fixed()
ggheatmap +
geom_text(aes(Var2, Var1, label = value), color = "black", size = 4) +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.ticks = element_blank(),
legend.justification = c(1, 0),
legend.position = c(0.6, 0.7),
legend.direction = "horizontal")+
guides(fill = guide_colorbar(barwidth = 7, barheight = 1,
title.position = "top", title.hjust = 0.5))Code
par(mfrow=c(1,1))
ccf_result <- ccf(normalized_data[, c("AMZN.Adjusted")], normalized_data[, c("gdp")],
lag.max = 300,
main = "Cros-Correlation Plot for AMZN Stock Price and GDP Growth Rate ",
ylab = "CCF")Code
cat("The sum of cross correlation function is", sum(abs(ccf_result$acf)))The sum of cross correlation function is 4.585922
Code
par(mfrow=c(1,1))
ccf_result <- ccf(normalized_data[, c("AMZN.Adjusted")], normalized_data[, c("interest")],
lag.max = 300,
main = "Cros-Correlation Plot for AMZN Stock Price and Interest Rate",
ylab = "CCF")Code
cat("The sum of cross correlation function is", sum(abs(ccf_result$acf)))The sum of cross correlation function is 11.29588
Code
par(mfrow=c(1,1))
ccf_result <- ccf(normalized_data[, c("AMZN.Adjusted")], normalized_data[, c("inflation")],
lag.max = 300,
main = "Cros-Correlation Plot for AMZN Stock Price and Inflation Rate",
ylab = "CCF")Code
cat("The sum of cross correlation function is", sum(abs(ccf_result$acf)))The sum of cross correlation function is 16.68466
Code
par(mfrow=c(1,1))
ccf_result <- ccf(normalized_data[, c("AMZN.Adjusted")], normalized_data[, c("unemployment")],
lag.max = 300,
main = "Cros-Correlation Plot for AMZN Stock Priceand Unemployment Rate",
ylab = "CCF")Code
cat("The sum of cross correlation function is", sum(abs(ccf_result$acf)))The sum of cross correlation function is 20.53876
The Normalized Time Series Data for Stock Price and Macroeconomic Variables plot shows the same variables as the first plot but has been normalized to a common range of 0 to 1 using the scale() function in R, which standardizes the variables to have a mean of 0 and a standard deviation of 1. The heatmap analysis of the normalized data reveals that inflation and unemployment rate exhibit strong positive correlations with the stock price indices, indicating that these variables may significantly influence stock price movements. On the other hand, weaker correlations were observed between the stock price indices and GDP and interest rates, suggesting that these variables may have less impact on stock price fluctuations. The cross-correlation feature plots confirm these findings, indicating that inflation and unemployment rate are more suitable feature variables for the ARIMAX model when predicting Amazon movements.
Final Exogenous variables: Macroeconomic indicators: Inflation rate and unemployment rate.
Enodogenous and Exogenous Variables Plot
Code
final_data <- final %>%dplyr::select( Date,AMZN.Adjusted, inflation,unemployment)
numeric_data <- c("AMZN.Adjusted", "inflation","unemployment")
numeric_data <- final_data[, numeric_data]
normalized_data_numeric <- scale(numeric_data)
normalized_numeric_df <- data.frame(normalized_data_numeric)
normalized_data_ts <- ts(normalized_data_numeric, start = c(2010, 1), frequency = 4)
autoplot(normalized_data_ts, facets=TRUE) +
xlab("Year") + ylab("") +
ggtitle("Amazon Stock Price, Inflation Rate and Unemployment Rate in USA 2010-2023")Code
# Convert your multivariate time series data to a matrix
final_data_ts_multivariate <- as.matrix(normalized_data_ts)
# Check for stationarity using Phillips-Perron test
phillips_perron_test <- ur.pp(final_data_ts_multivariate)
summary(phillips_perron_test)
##################################
# Phillips-Perron Unit Root Test #
##################################
Test regression with intercept
Call:
lm(formula = y ~ y.l1)
Residuals:
Min 1Q Median 3Q Max
-1.4360 -0.1440 -0.0602 0.0993 4.5029
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.0001847 0.0403454 0.005 0.996
y.l1 0.8645022 0.0407542 21.213 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.5023 on 153 degrees of freedom
Multiple R-squared: 0.7463, Adjusted R-squared: 0.7446
F-statistic: 450 on 1 and 153 DF, p-value: < 2.2e-16
Value of test-statistic, type: Z-alpha is: -22.0542
aux. Z statistics
Z-tau-mu 0.0055
The results of the Phillips-Perron unit root test indicate strong evidence against the null hypothesis of a unit root, as the p-value for the coefficient of the lagged variable is less than the significance level of 0.05. This suggests that the variable y, which is being tested for stationarity, is likely stationary. Furthermore, the test statistic Z-tau-mu is 0.0055, which is smaller than the critical value of Z-alpha (-22.0542), providing further evidence of stationarity.
To determine whether the linear model requires an ARCH model, an ARCH test is conducted. The ACF and PACF plots are also used to identify suitable model values.
Model Fitting
Code
normalized_numeric_df$AMZN.Adjusted<-ts(normalized_numeric_df$AMZN.Adjusted,star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
normalized_numeric_df$inflation<-ts(normalized_numeric_df$inflation,star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
normalized_numeric_df$unemployment<-ts(normalized_numeric_df$unemployment,star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
fit <- lm(AMZN.Adjusted ~ inflation+unemployment, data=normalized_numeric_df)
fit.res<-ts(residuals(fit),star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
############## Then look at the residuals ############
returns <- fit.res %>% diff()
autoplot(returns)+ggtitle("Linear Model Returns")Code
byd.archTest <- ArchTest(fit.res, lags = 1, demean = TRUE)
byd.archTest
ARCH LM-test; Null hypothesis: no ARCH effects
data: fit.res
Chi-squared = 36.896, df = 1, p-value = 1.246e-09
Code
ggAcf(returns) +ggtitle("ACF for returns")Code
ggPacf(returns) +ggtitle("PACF for returns")The ARCH LM-test was conducted with the null hypothesis of no ARCH effects. The test resulted in a chi-squared value of 36.896 with one degree of freedom, and a very low p-value of 1.246e-09. This suggests strong evidence against the null hypothesis, indicating the presence of ARCH effects in the data.
Based on the ACF and PACF plots, it appears that there is some significant autocorrelation and partial autocorrelation at multiple lags, which suggests that an ARIMA model may not be sufficient to capture the time series behavior. Additionally, the values for p and q appear to be relatively high, with p = 1 and q = 1 being suggested by the plots.
ARIMAX Model
Code
xreg <- cbind(Inflation = normalized_data_ts[, "inflation"],
Unemployment = normalized_data_ts[, "unemployment"])
fit.auto <- auto.arima(normalized_data_ts[, "AMZN.Adjusted"], xreg = xreg)
summary(fit.auto)Series: normalized_data_ts[, "AMZN.Adjusted"]
Regression with ARIMA(0,1,0) errors
Coefficients:
Inflation Unemployment
0.0625 -0.0687
s.e. 0.0966 0.0438
sigma^2 = 0.04933: log likelihood = 5.39
AIC=-4.78 AICc=-4.27 BIC=1.01
Training set error measures:
ME RMSE MAE MPE MAPE MASE ACF1
Training set 0.03057732 0.215598 0.1225672 11.69566 31.46174 0.408043 0.1470963
Code
checkresiduals(fit.auto)
Ljung-Box test
data: Residuals from Regression with ARIMA(0,1,0) errors
Q* = 4.4858, df = 8, p-value = 0.8109
Model df: 0. Total lags used: 8
Code
set.seed(1234)
model_output <- capture.output(sarima(fit.res, 1,1,1)) Code
cat(model_output[30:61], model_output[length(model_output)], sep = "\n")Call:
arima(x = xdata, order = c(p, d, q), seasonal = list(order = c(P, D, Q), period = S),
xreg = constant, transform.pars = trans, fixed = fixed, optim.control = list(trace = trc,
REPORT = 1, reltol = tol))
Coefficients:
ar1 ma1 constant
0.6076 -0.2899 -0.0064
s.e. 0.2341 0.2628 0.0647
sigma^2 estimated as 0.06782: log likelihood = -3.83, aic = 15.66
$degrees_of_freedom
[1] 48
$ttable
Estimate SE t.value p.value
ar1 0.6076 0.2341 2.5960 0.0125
ma1 -0.2899 0.2628 -1.1031 0.2755
constant -0.0064 0.0647 -0.0984 0.9220
$AIC
[1] 0.3070239
$AICc
[1] 0.3170364
$BIC
[1] 0.4585396
NA
NA
Code
n=length(fit.res)
k= 51
rmse1 <- matrix(NA, (n-k),4)
rmse2 <- matrix(NA, (n-k),4)
rmse3 <- matrix(NA, (n-k),4)
st <- tsp(fit.res)[1]+(k-5)/4
for(i in 1:(n-k))
{
xtrain <- window(fit.res, end=st + i/4)
xtest <- window(fit.res, start=st + (i+1)/4, end=st + (i+4)/4)
#ARIMA(0,1,0) ARIMA(1,1,1)
fit <- Arima(xtrain, order=c(0,1,0),
include.drift=TRUE, method="ML")
fcast <- forecast(fit, h=4)
fit2 <- Arima(xtrain, order=c(1,1,1),
include.drift=TRUE, method="ML")
fcast2 <- forecast(fit2, h=4)
rmse1[i,1:length(xtest)] <- sqrt((fcast$mean-xtest)^2)
rmse2[i,1:length(xtest)] <- sqrt((fcast2$mean-xtest)^2)
}
plot(1:4,colMeans(rmse1,na.rm=TRUE), type="l",col=2, xlab="horizon", ylab="RMSE")
lines(1:4, colMeans(rmse2,na.rm=TRUE), type="l",col=3)
legend("topleft",legend=c("fit1","fit2"),col=2:4,lty=1)Based on the results of the auto.arima function, the suggested best model is ARIMA(0,1,0), but the acf and pacf plots suggest a simpler ARIMA(1,1,1) model. To determine the best model, we conduct cross-validation and compare the RMSE values of both models. The results show that ARIMA(1,1,1) has lower RMSE values than ARIMA(0,1,0), indicating that it is the better model.
We can then proceed to choose the best GARCH model using ARIMA(1,1,1) as the base model.
Squared Residuals
Code
fit <- lm(AMZN.Adjusted ~ inflation+unemployment, data=normalized_numeric_df)
fit.res<-ts(residuals(fit),star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
fit <- Arima(fit.res,order=c(1,1,1))
res=fit$res
plot(res^2,main='Squared Residuals')Code
acf(res^2,24, main = "ACF Residuals Square")Code
pacf(res^2,24, main = "PACF Residuals Square")Code
summary(garchFit(~garch(1,1),res, trace=F))
Title:
GARCH Modelling
Call:
garchFit(formula = ~garch(1, 1), data = res, trace = F)
Mean and Variance Equation:
data ~ garch(1, 1)
<environment: 0x1557b63a0>
[data = res]
Conditional Distribution:
norm
Coefficient(s):
mu omega alpha1 beta1
-0.00530411 0.00068953 0.48627960 0.65780719
Std. Errors:
based on Hessian
Error Analysis:
Estimate Std. Error t value Pr(>|t|)
mu -0.0053041 0.0155220 -0.342 0.7326
omega 0.0006895 0.0011861 0.581 0.5610
alpha1 0.4862796 0.2392140 2.033 0.0421 *
beta1 0.6578072 0.1208067 5.445 5.18e-08 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Log Likelihood:
9.169268 normalized: 0.1763321
Description:
Tue Jan 9 20:58:23 2024 by user:
Standardised Residuals Tests:
Statistic p-Value
Jarque-Bera Test R Chi^2 1.08557 0.5811275
Shapiro-Wilk Test R W 0.9616717 0.09248575
Ljung-Box Test R Q(10) 5.843556 0.8282312
Ljung-Box Test R Q(15) 8.260042 0.9129345
Ljung-Box Test R Q(20) 15.71232 0.7343031
Ljung-Box Test R^2 Q(10) 9.933015 0.4463896
Ljung-Box Test R^2 Q(15) 11.22686 0.7363534
Ljung-Box Test R^2 Q(20) 13.8952 0.8357696
LM Arch Test R TR^2 13.33945 0.3448583
Information Criterion Statistics:
AIC BIC SIC HQIC
-0.19881801 -0.04872234 -0.20956333 -0.14127488
From the squared residuals of the best ARIMA model, it can be observed that the ACF plot and PACF plot indicate that the residuals are not autocorrelated and are white noise, indicating a good fit of the model. Based on the squared residuals of the best ARIMA model, we can see that the ACF and PACF plots indicate that most of the values lie between the blue lines. Additionally, the p-value is 1 and q-value is 1. This suggests that the model has a good fit and that there is no significant autocorrelation or partial autocorrelation in the residuals.
The bst model is ARIMA(1,1,1) and GARCH(1,1). #### Best Model
Code
#fiting an ARIMA model to the Inflation variable
inflation_fit<-auto.arima(normalized_numeric_df$inflation)
finflation<-forecast(inflation_fit)
#fitting an ARIMA model to the Unemployment variable
unemployment_fit<-auto.arima(normalized_numeric_df$unemployment)
funemployment<-forecast(unemployment_fit)
# best model fit for forcasting
xreg <- cbind(Inflation = normalized_data_ts[, "inflation"],
Unemployment = normalized_data_ts[, "unemployment"])
summary(arima.fit<-Arima(normalized_data_ts[, "AMZN.Adjusted"],order=c(1,1,1),xreg=xreg),include.drift = TRUE)Series: normalized_data_ts[, "AMZN.Adjusted"]
Regression with ARIMA(1,1,1) errors
Coefficients:
ar1 ma1 Inflation Unemployment
-0.5637 1.0000 -0.0025 -0.0790
s.e. 0.1390 0.0573 0.0949 0.0336
sigma^2 = 0.0412: log likelihood = 9.68
AIC=-9.36 AICc=-8.03 BIC=0.3
Training set error measures:
ME RMSE MAE MPE MAPE MASE
Training set 0.02911543 0.1929808 0.114944 11.94347 27.98997 0.3826642
ACF1
Training set -0.06750725
Code
summary(final.fit <- garchFit(~garch(1,1), res,trace = F))
Title:
GARCH Modelling
Call:
garchFit(formula = ~garch(1, 1), data = res, trace = F)
Mean and Variance Equation:
data ~ garch(1, 1)
<environment: 0x15548d140>
[data = res]
Conditional Distribution:
norm
Coefficient(s):
mu omega alpha1 beta1
-0.00530411 0.00068953 0.48627960 0.65780719
Std. Errors:
based on Hessian
Error Analysis:
Estimate Std. Error t value Pr(>|t|)
mu -0.0053041 0.0155220 -0.342 0.7326
omega 0.0006895 0.0011861 0.581 0.5610
alpha1 0.4862796 0.2392140 2.033 0.0421 *
beta1 0.6578072 0.1208067 5.445 5.18e-08 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Log Likelihood:
9.169268 normalized: 0.1763321
Description:
Tue Jan 9 20:58:24 2024 by user:
Standardised Residuals Tests:
Statistic p-Value
Jarque-Bera Test R Chi^2 1.08557 0.5811275
Shapiro-Wilk Test R W 0.9616717 0.09248575
Ljung-Box Test R Q(10) 5.843556 0.8282312
Ljung-Box Test R Q(15) 8.260042 0.9129345
Ljung-Box Test R Q(20) 15.71232 0.7343031
Ljung-Box Test R^2 Q(10) 9.933015 0.4463896
Ljung-Box Test R^2 Q(15) 11.22686 0.7363534
Ljung-Box Test R^2 Q(20) 13.8952 0.8357696
LM Arch Test R TR^2 13.33945 0.3448583
Information Criterion Statistics:
AIC BIC SIC HQIC
-0.19881801 -0.04872234 -0.20956333 -0.14127488
Code
ht <- final.fit@h.t #a numeric vector with the conditional variances (h.t = sigma.t^delta)
#############################
data=data.frame(final)
data$Date<-as.Date(data$Date,"%Y-%m-%d")
data2= data.frame(ht,data$Date)
ggplot(data2, aes(y = ht, x = data.Date)) + geom_line(col = '#7FB3D5') + ylab('Conditional Variance') + xlab('Date')From the ARIMA(1,1,1), we see that the training set error measures also suggest a good fit, with low mean absolute error, root mean squared error, and autocorrelation of the residuals. GATCH(1,1) model model is used to estimate the volatility of the standardized residuals of the previous regression model. The model includes a mean equation that estimates the mean of the residuals and a variance equation that models the conditional variance of the residuals. The coefficients of the mean equation suggest that the mean of the residuals is close to zero. The variance equation coefficients suggest that the conditional variance of the residuals is dependent on the past conditional variances and the past squared standardized residuals. The model’s the AIC, BIC, SIC, and HQIC values are all relatively low, indicating a good fit of the model. The standardized residuals tests indicate that the residuals are approximately normally distributed and that there is no significant autocorrelation in the residuals.
The volatility of the model seems high in 2020 but has decreased gradually in the past few months. This could indicate that the asset’s price was experiencing a lot of fluctuations in 2020, but the market has stabilized recently.
Model Diagnostics
Code
fit2<-garch(res,order=c(1,1),trace=F)
checkresiduals(fit2) Code
qqnorm(fit2$residuals, pch = 1)
qqline(fit2$residuals, col = "blue", lwd = 2)Code
Box.test (fit2$residuals, type = "Ljung")
Box-Ljung test
data: fit2$residuals
X-squared = 2.0187, df = 1, p-value = 0.1554
The ACF plot of the residuals shows all the values between the blue lines, which indicates that the residuals are not significantly autocorrelated. The range of values for the residual plot between -2 and 2 is considered acceptable. Additionally, the QQ plot of the residuals shows a linear plot on the line, which is another good indication that the residuals are normally distributed. The QQ plot is a valuable tool to assess if the residuals follow a normal distribution, and in this case, the plot suggests that the residuals do indeed follow a normal distribution.
The Box-Ljung test, a p-value of 0.1554 indicates that the model’s residuals are not significantly autocorrelated, meaning that the model has captured most of the information in the data. This result is good because it suggests that the model is a good fit for the data and has accounted for most of the underlying patterns in the data. Therefore, we can rely on the model’s predictions and use them to make informed decisions.
Forecast
Code
predict(final.fit, n.ahead = 5, plot=TRUE) meanForecast meanError standardDeviation lowerInterval upperInterval
1 -0.005304111 0.5028875 0.5028875 -0.9909454 0.9803372
2 -0.005304111 0.5385390 0.5385390 -1.0608212 1.0502130
3 -0.005304111 0.5766303 0.5766303 -1.1354787 1.1248705
4 -0.005304111 0.6173340 0.6173340 -1.2152565 1.2046483
5 -0.005304111 0.6608347 0.6608347 -1.3005162 1.2899080
The forecasted plot is based on the best model ARIMAX(1,1,1)+GARCH(1,1). This model takes into account the autoregressive and moving average components of the data, as well as the impact off exogenous variables on the time series. Additionally, the GARCH component of the model accounts for the volatility clustering in the data. Overall, this model is well-suited to make accurate predictions about future values of the time series.
Equation of the Model
The equation of the ARIMAX(1,1,1) model is:
\(Y(t) = c + \phi_1(Y{(t-1)} - X{(t-1)}) + \theta_1\epsilon{(t-1)} + \epsilon(t)\)
where, \(Y(t)\) is the time series variable, \(X(t-1)\) is the exogenous variable, \(c\) is a constant, \(\phi_1\) and \(\theta_1\) are the parameters, and \(\epsilon(t)\) is the error term.
The equation of the GARCH(1,1) model is:
\(\sigma^2(t) = \alpha_0+\alpha_1\epsilon_t^2(t-1)+ \beta_1\sigma^2(t-1)\)
where \(\sigma^2_t\) is the conditional variance at time \(t\), \(\alpha_0\) is a constant, \(\alpha_1\) and \(\beta_1\) are the parameters, and \(\epsilon_t\) is the error term.
The combined equation of the ARIMAX(1,1,1)+GARCH(1,1) model is:
\(Y(t) = c + \phi_1(Y(t-1) - X(t-1)) + \theta_1\epsilon(t-1) + \epsilon(t)\)
\(\epsilon(t) = \sigma(t) * \epsilon~(t)\)
\(\sigma^2(t) = \alpha_0+\alpha_1\epsilon_t^2(t-1)+ \beta_1\sigma^2(t-1)\)